package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.util.EmailUtil;
import com.qf.util.MD5Util;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public boolean checkUserName(String username) {
        User user = userDao.selectByUserName(username);
        if (user != null) {
            return true;//用户已存在
        }
        return false;//用户可用
    }

    @Override
    public void regist(User user) {
        //密码加密
        user.setPassword(MD5Util.md5(user.getPassword()));
        userDao.insert(user);
        //发送邮件
        EmailUtil.sendEmail(user);
    }

    @Override
    public void activate(String email, String code) {
        int result = userDao.updateFlag(email,code);
    }

    @Override//登录
    public User login(String username, String password) {
        //加密
        password=MD5Util.md5(password);
        //查找用户
        User user = userDao.selectByUserName(username);
        //判断
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        //比较密码
        if(!user.getPassword().equalsIgnoreCase(password)){
            throw new RuntimeException("密码错误");
        }
        if(user.getFlag()!=1){
            throw new RuntimeException("账户未激活或已失效");
        }
        return user;
    }
}
